<template>
  <!--矩形边框 -->
  <div
    class="frame_node"
    :style="boxStyle"
    @click.stop="pannelClick">
    <el-input
      v-if="shapeNode.shapeKey === ShapeKeyEnum.SimulationTextField"
      ref="inputRef"
      v-model="nodeValue"
      size="small"
      :style="{
        ...baseStyle,
        border:'none',
        lineHeight: (shapeNode.style.fontSize || 12) + 2 + 'px',
      }"
      @blur="handleValueChange"
      @keyup.enter="handleValueChange" />

    <button
      v-if="shapeNode.shapeKey === ShapeKeyEnum.SimulationButton"
      :style="{
        ...baseStyle,
        width: shapeNode.style.width - 2 + 'px',
        height: shapeNode.style.height - 1 + 'px',
        border: 'none',
        cursor: 'pointer',
        overflow: 'hidden',
        whiteSpace: 'nowrap',
        textOverflow: 'ellipsis',
      }"
      @click.stop="handleButtonClick">
      {{ shapeNode.showText }}
    </button>

    <img
      v-else-if="shapeNode.shapeKey === ShapeKeyEnum.ImageShape"
      :src="getModelIcon(shapeNode.icon)"
      style="width: 100%; height: 100%; object-fit: contain;"
      draggable="false"
      class="_icon" />

    <span
      v-else-if="shapeNode.shapeKey === ShapeKeyEnum.SimulationLabel"
      class="cuie_shape-span"
      :style="{
        fontStyle: shapeNode.style.fontStyle || 'normal',
        whiteSpace: 'nowrap',
        textOverflow: 'ellipsis',
        width: '100%',
        overflow: 'hidden'
      }">
      {{shapeNode.propertyId ? isNaN(Number(props.shapeNode.propertyData.value)) ? props.shapeNode.propertyData.value : Number(Number(props.shapeNode.propertyData.value).toFixed(4)) * 10000 / 10000 : shapeNode.showText}}
    </span>

    <UINode v-for="node in shapeNode.children" :key="node.modelId" :shape-node="node" />
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, onMounted } from "vue";
import { ADCUICoreNode, ShapeKeyEnum, UIDataType } from "@/constants/types";
import { throttle } from "lodash";
import { useI18n } from "vue-i18n";
import { controller } from "@/engine/Controller";
import { MODEL_SERVER_URL } from "@/constants/constants";

const { t } = useI18n();

const props = defineProps<{
  shapeNode: ADCUICoreNode;
}>();

const k =  Number(Number(props.shapeNode.propertyData.value).toFixed(4)) * 10000 / 10000;

const nodeValue = props.shapeNode.propertyData.value ? ref(String(props.shapeNode.propertyData.value)) : ref(props.shapeNode.showText);
let oldNodeValue = nodeValue.value;
const invalidValue = ref(false);
const inputHeight = ref(props.shapeNode.style.height + "px");
const inputFontStyle = ref(props.shapeNode.style.fontStyle);
const inputFontWeight = ref(props.shapeNode.style.fontWeight);
const inputBoder = ref(props.shapeNode.style.border);
const bgColor = ref(props.shapeNode.style.background);
const textColor = ref(props.shapeNode.style.color);
const baseStyle = computed(() => {
  const { color, fontSize, fontWeight, fontFamily, background, border, textAlign, fontStyle } = props.shapeNode.style;
  return {
    color: color,
    fontSize: fontSize + 'px',
    fontWeight: fontWeight,
    fontFamily: fontFamily,
    background: background,
    border: border,
    textAlign: textAlign as any,
    fontStyle: fontStyle || 'normal',
  };
});
const boxStyle = computed(() => {
  const { x, y, width, height } = props.shapeNode.style;
  let style = {
    left: x + 'px',
    top: y + 'px',
    width: width + 'px',
    height: height + 'px',
  } as any;
  if (props.shapeNode.shapeKey !== ShapeKeyEnum.ImageShape) {
    style = Object.assign(style, baseStyle.value);
  }
  if (props.shapeNode.imageInfo) {
    style.background = `url(${props.shapeNode.imageInfo.url}) no-repeat center/contain`;
  }
  return style;
});

const getModelIcon = (icon?: string) => {
  if (!icon || icon === '') {
    return '';
  }
  if (icon.startsWith('statics/') || icon.startsWith(MODEL_SERVER_URL) || icon.startsWith('/statics/')) {
    return icon;
  } else {
    return MODEL_SERVER_URL + '/public/files/' + controller.simUIService.projectId + '/' + icon;
  }
};

const handleValueChange = () => {
  const valueType = props.shapeNode.valueType;
  console.log('valueType: ', valueType);
  let value = nodeValue.value;
  if (['Integer', 'Real'].includes(valueType)) {
    const nV = Number(value);
    invalidValue.value = isNaN(nV) ? true : false;
  } else if (valueType === "Boolean") {
    value = String(value);
    invalidValue.value = ["true", "false"].includes(value) ? false : true;
  }
  if (invalidValue.value) {
    app.$confirm
      .popup({
        title: t('err'),
        subTitle: t('in_invalid'),
        content: t('in_va_style'),
        cancelText: t('close'),
        okText: "",
        status: "error",
        width: 292
      })
      .finally(() => {
        nodeValue.value = oldNodeValue;
      });
    return;
  }
  controller.simUIService.uiDataChangeNoteBackend(props.shapeNode.objectId, props.shapeNode.propertyId, [nodeValue.value!]);
};
const handleButtonClick = throttle(() => {
  console.log("信号点击props.shapeNode:", props.shapeNode);
  if (props.shapeNode.propertyId && props.shapeNode.objectId) {
    controller.simUIService.uiButtonClick(props.shapeNode.propertyId, props.shapeNode.objectId);
  }
}, 500);

const pannelClick = throttle(() => {
  console.log("pannelClickpannelClick", props.shapeNode);
  if (props.shapeNode.imageInfo && props.shapeNode.imageInfo?.signal?.elementId) {
    controller.simApi.uiClickButton({
      elementId: props.shapeNode.imageInfo.signal.elementId,
      simulationSessionId: props.shapeNode.imageInfo.signal.simulationSessionId,
      contextId: props.shapeNode.objectId, // differ to imageswitcher, this use ui-objectId as contextid
    });
  }
}, 500);

watch(
  () => props.shapeNode.propertyData,
  () => {
    nodeValue.value = String(props.shapeNode.propertyData.value);
    oldNodeValue = nodeValue.value;
    inputHeight.value = props.shapeNode.style.height + "px";
    bgColor.value = props.shapeNode.style.background;
    textColor.value = props.shapeNode.style.color;
    inputFontStyle.value = props.shapeNode.style.fontStyle;
    inputFontWeight.value = props.shapeNode.style.fontWeight;
    inputBoder.value = props.shapeNode.style.border;
  },
  { deep: true }
);
onMounted(async () => {
  if (props.shapeNode.valueType === UIDataType.Enumeration) {
    // fail to update in [treeForeach]
    const enumModelInfo = (await controller.modelApi.modelInfo({ modelId: props.shapeNode?.propertyData.value, projectId: controller.simUIService.projectId })).data?.data;
    if (enumModelInfo) {
      nodeValue.value = enumModelInfo.name; // for input
      props.shapeNode.propertyData.value = enumModelInfo.name; // for label
    }
  }
});
</script>
<style lang="scss">
.frame_node {
  display: flex;
  justify-content: center;
  flex-direction:column;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  box-sizing: border-box;
  position: absolute;
  >.el-input {
    border: none;
    box-sizing: content-box;
    background-color: v-bind(bgColor);
    .el-input__inner {
      width: 100%;
      height: v-bind(inputHeight);
      border: v-bind(inputBoder);
      background-color: v-bind(bgColor);
      color: v-bind(textColor);
      padding-left: 0;
      padding-right: 0;
      font-style: v-bind(inputFontStyle);
      font-weight: v-bind(inputFontWeight);
    }
  }
}
</style>
